package com.zae.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zae.io.Resources;
import com.zae.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 解析sqlMapConfig.xml文件存放在javaBean中
 */
public class XmlConfigBuilder {

    private Configuration  configuration;

    public XmlConfigBuilder(){
        this.configuration = new Configuration();
    }

    /**
     * 解析sqlMapConfig.xml文件
     * @param inputStream
     * @return
     */
    public Configuration parasConfig(InputStream inputStream) throws Exception{
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        //获取根标签里面的内容
        Element rootElement = document.getRootElement();
        //获取所有的property标签里面的内容
        List<Element> list = rootElement.selectNodes("//property");
        //将数据库连接信息读取到properties文件中
        Properties properties = new Properties();
        for (Element element : list) {
            //获取子标签里面的属性
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        //创建数据库连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("dataDriver"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("dataUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        //给configuration里面的数据源属性赋值
        configuration.setDataSource(comboPooledDataSource);

        //解析xl文件的数据
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            //获取到mapper.xml文件的路径
            String resource = element.attributeValue("resource");
            //获取mapper文件的输入流
            InputStream mapperInputStream = Resources.getInputStreamByXml(resource);
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parasMapper(mapperInputStream);
        }


        return configuration;
    }
}
